package com.xdap.common.service.impl;

import com.definesys.mpaas.common.http.Response;
import com.xdap.common.dao.ComApaasDataModelDao;
import com.xdap.common.pojo.dto.CommonFixDataDto;
import com.xdap.common.pojo.po.ComApaasDataModel;
import com.xdap.common.service.CommonFixDataService;
import com.xdap.common.util.ComApaasTokenUtil;
import com.xdap.common.util.ComRestClient;
import com.xdap.common.util.GsonUtil;
import com.xdap.motor.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Service
public class CommonFixDataServiceImpl implements CommonFixDataService {
    @Autowired
    private ComRestClient comRestClient;
    @Autowired
    private ComApaasDataModelDao comApaasDataModelDao;
    @Value("${xdap.plugin.store.prefix}")
    private String storePrefix;
    @Resource
    private ComApaasTokenUtil comApaasTokenUtil;

    @Override
    public String fixData(CommonFixDataDto fixDataDto) {
        List<String> modelCodes = null;
        // 根据条件，或者是查询全量的需要修复的数据--如果有传入的参数，则只根据传入的参数进行处理
        if (fixDataDto != null && StringUtils.isNotBlank(fixDataDto.getModelCode())) {
            String[] split = fixDataDto.getModelCode().split(",");
            modelCodes = Arrays.asList(split);
        }
        List<ComApaasDataModel> apaasDataModels = comApaasDataModelDao.queryNeedFixModel(modelCodes);
        // 根据条件获取到对应的需要修复表单，确定有表单的情况下，进行处理
        if (CollectionUtils.isEmpty(apaasDataModels)) {
            return "未找到合适的需要修复的数据";
        }
        HttpHeaders httpHeaders = comApaasTokenUtil.dealApaasHeaders();
        String result = "已经初始化对应模型：";
        // 拆解download的地址，获取后端地址
        String singleAdminAppUrl = storePrefix.split("/xdap-plugin")[0];
        String url = singleAdminAppUrl + "/xdap-app/dataModel/fix/businessData";
        for (ComApaasDataModel apaasDataMode : apaasDataModels) {

            String modelName = apaasDataMode.getModelName();
            String modelCode = apaasDataMode.getModelCode();
            Response resp = (Response) comRestClient.post(url,
                    GsonUtil.toJson(apaasDataMode), new Response(), httpHeaders);
            String code = resp.getCode();
            if (Response.CODE_ERR.equals(code)) {
                result += modelName + ":" + modelCode + "(执行失败);";
            } else {
                result += modelName + ":" + modelCode + "(执行成功);";
            }

        }


        return result;
    }



}
